package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/trim-a-binary-search-tree/
 */
public class Title108 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public TreeNode sortedArrayToBST(int[] nums) {
        return traversal(nums, 0, nums.length - 1);
    }

    public TreeNode traversal(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }
        int middle = (start + end) / 2;
        TreeNode root = new TreeNode(nums[middle]);
        root.left = traversal(nums, start, middle - 1);
        root.right = traversal(nums, middle + 1, end);
        return root;
    }








    public TreeNode sortedArrayToBST2(int[] nums) {
        return traversal1(nums, 0, nums.length - 1);

    }

    private TreeNode traversal1(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        int middle = left + (right - left) / 2;
        TreeNode root = new TreeNode(nums[middle]);
        root.left = traversal1(nums, left, middle - 1);
        root.right = traversal1(nums, middle + 1, right);
        return root;
    }

    public static void main(String[] args) {

    }
}
